package com.wcsy.myblog.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcsy.myblog.dao.*;
import com.wcsy.myblog.entity.*;
import com.wcsy.myblog.filter.SensitiveFilter;
import com.wcsy.myblog.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper,Article> implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    ITypeService iTypeService;
    @Autowired
    NumServiceImpl numService;
    @Autowired
    LabelMapper labelMapper;
    @Autowired
    ILabelService iLabelService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ImgMapper imgMapper;
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    ILkplusService iLkplusService;
    @Autowired
    IUserService iUserService;
    @Autowired
    CollectMapper collectMapper;
    @Override
    public List<Article> selectArticle(String name) {
        return articleMapper.selectArticle(name);
    }

    @Override
    public Map<String, Object> selectList() {
       Map<String, Object> map = new LinkedHashMap<>();
        //文章点赞数前六
        List<Article> articles = articleMapper.selectList();
        //按照点赞数进行排序
        articles.sort((x,y)->Integer.compare((int)x.getArticleLike(),(int) y.getArticleLike()));
        descend(articles);
        //点赞数前六的文章
        map.put("articlesLike",articles);

        List<Article> articlePviw = articleMapper.selectList();
        articles.sort((x,y)->Integer.compare((int)x.getPageviews(),(int) y.getPageviews()));
        descend(articlePviw);
        //浏览数前六的文章
        map.put("articlesPageview",articlePviw);
        return map;
    }

    /**
     * 对文章字段升序变降序
     * @param articles
     */
    public static void descend(List<Article> articles){
        Stack<Article> stack = new Stack<>();
        for (int i = 0; i < articles.size(); i++) {
            //保存进栈
            stack.push( articles.get(i));
        }
        articles.clear();
        for (int i = 0; i < 6; i++) {
            //弹栈
            articles.add(stack.pop());
        }
    }

    @Override
    public List<Article> select(String name) {
        return articleMapper.select(name);
    }

    @Override
    public void insertArticle(Article article,Label label,
                              String typeName,String typeKidName) throws Exception {
        Date date = new Date(System.currentTimeMillis());
        String format = new SimpleDateFormat("YYYY年MM月dd日HH:mm").format(date);
       User user = (User) session.getAttribute("user");
//        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", 1));
        //判断 如果用户输入的文章标签是新标签，则添加
        boolean b = iLabelService.insertLable(label);
        //根据标签名查出标签id
        Label lablessss= labelMapper.selectId(label.getLabelName());
        //判断 如果用户输入的文章类型是新类型 ，则添加
        int typeId = iTypeService.insertType(typeName, typeKidName);
        //确定文章标题是不是敏感词汇
        String getfilter = numService.getfilter(article.getArticleName());
        if(!getfilter.equals(article.getArticleName())){
            System.out.println("请勿输入敏感词汇");
            return;
        }

        //确定文章内容中是不是含有敏感词汇
        String getfilter1 = numService.getfilter(article.getArticleContent());
        article.setArticleContent(getfilter1);
        article.setAddTime(format);
        article.setLabel(lablessss.getLabelId());
        article.setUserId(user.getUserId());
        article.setArticleLike(0L);
        article.setPageviews(0L);
        article.setType(typeId);
        articleMapper.insertArticle(article);
        try {
            //添加成功后,根据文章内容，用户id，类型id，标签id查询文章id
            Article article1 = articleMapper.selectId(article);
            //根据文章id将文章url写进去 "http://localhost:8081/article/selecteArticl?articleId="+article1.getArticleId()
            articleMapper.updateUrl("http://localhost:8081/article/selectArticle?articleId="+article1.getArticleId(),(int)article1.getArticleId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Article serlectOneArticle(Integer id) {

        return articleMapper.serlectOneArticle(id);
    }

    @Override
    public ArticlePage<Article> PageSelect(int pageNo) {
        //查询总行数
        Integer count = articleMapper.selectCount(null);
        //计算出有多少页
        int pageCount = count % ArticlePage.PAGE_SIZE == 0 ? count / ArticlePage.PAGE_SIZE : count / ArticlePage.PAGE_SIZE + 1;
        /*分页查询,查询当前页面的数据    因为是pageNo 是下标  所以要用pageNo - 1
          从(pageNo - 1) * ArticlePage.PAGE_SIZE条数据开始查起，查询往后ArticlePage.PAGE_SIZE条数据显示到页面 */
        List<Article> articles = articleMapper.sevletlimit((pageNo - 1) * ArticlePage.PAGE_SIZE, ArticlePage.PAGE_SIZE);
        ArticlePage page = new ArticlePage();
        page.setPageCount(pageCount);
        page.setPageNO(pageNo);
        page.setData(articles);
        return page;
    }

    @Override
    public ArticlePage<Article> PageUserSelect(int pageNo, int userId) {
        //查询总行数 20
        Integer count = articleMapper.selectCount(new QueryWrapper<Article>().eq("user_id",userId));
        //计算出有多少页
        int pageCount = count % ArticlePage.PAGE_SIZE == 0 ? count / ArticlePage.PAGE_SIZE : count / ArticlePage.PAGE_SIZE + 1;
        /*分页查询,查询当前页面的数据    因为是pageNo 是下标  所以要用pageNo - 1
          从(pageNo - 1) * ArticlePage.PAGE_SIZE条数据开始查起，查询往后ArticlePage.PAGE_SIZE条数据显示到页面 */
        List<Article> articles = articleMapper.sevletUserlimit((pageNo - 1) * ArticlePage.PAGE_SIZE, ArticlePage.PAGE_SIZE,userId);
        ArticlePage page = new ArticlePage();
        page.setPageCount(pageCount);
        page.setPageNO(pageNo);
        page.setData(articles);
        return page;
    }

    @Override
    public List<Article> SelectListCollect(int userId) {
        return articleMapper.SelectListCollect(userId);
    }

    @Override
    public boolean updateArticle(Article article) {
        Article oneArticle = articleMapper.selectOneArticle((int)article.getArticleId());
        Date date = new Date(System.currentTimeMillis());
        String format = new SimpleDateFormat("YYYY年MM月dd日HH:mm").format(date);
        article.setUpdateTime(format);
        if (article.getArticleContent()==null){
           article.setArticleContent(oneArticle.getArticleContent());
        }
        if (article.getArticleName()==null){
            article.setArticleName(oneArticle.getArticleName());
        }
        boolean b = articleMapper.updateArticle(article);
        return b;
    }

    @Override
    public void updateNublike(int articleID,boolean toLike) throws Exception {
        User user = (User) session.getAttribute("user");
//        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", 1));
        //根据用户和文章id查出点赞id
        Lkplus one = iLkplusService.getOne(new QueryWrapper<Lkplus>().
                eq("user_id", user.getUserId()).
                eq("article_id", articleID));

        Article article = articleMapper.selectOneArticle(articleID);
        //点赞
        if (toLike && one ==null){
            //存入点赞表
            Lkplus lkplus = new Lkplus();
            lkplus.setUserId(article.getUserId());
            lkplus.setArticleId(articleID);
            iLkplusService.insertLkpuls(lkplus);
                //给当前文章的点赞数+1
                articleMapper.updateNubArticle(articleID);
                //存入点赞表
                user.setNoLike(user.getNoLike()+1);
                iUserService.update(user,new QueryWrapper<User>().eq("user_id",user.getUserId()));
                return;
        }else if (toLike==false && one !=null){ //取消点赞
             iLkplusService.deleteLkpuls((int)user.getUserId(),articleID);
            //给当前文章的点赞数-1
             articleMapper.noUpdateNubArticle(articleID);
            //给给用户的点赞数-1
//             userMapper.updateNubUser((int) article.getUserId());
            //存入点赞表
            user.setNoLike(user.getNoLike()-1);
            iUserService.update(user,new QueryWrapper<User>().eq("user_id",article.getUserId()));
        }
    }

    @Override
    public void insertCollect(int articleId) {
        User user = (User) session.getAttribute("user");
        Collect one = collectMapper.selectOne(new QueryWrapper<Collect>().
                eq("user_id", user.getUserId()).eq("article_id", articleId));
        if (one!=null) {
            articleMapper.insertCollect((int) user.getUserId(), articleId);
        }else {
            throw new NullPointerException("用户已经收藏这篇文章");
        }

    }

    @Override
    public void updatePageviews(int articleId) {
        articleMapper.updatePageviews(articleId);
    }

    @Override
    public void removeArticle(int id) {
        articleMapper.removeArticle(id);
    }
}
